//
//  SearchViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/6.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "ZZLayout.h"
#import "SearchNaviBarView.h"
#import "SearchSectionHeader.h"
#import "HomeADItemEventModel.h"

#import "SearchKeyWordItemCell.h"
#import "SearchResultSegViewController.h"

#import "SearchViewController.h"

@interface SearchViewController ()<UITextFieldDelegate,UICollectionViewDataSource, UICollectionViewDelegate,ZZLayoutDelegate>

@property (nonatomic, strong) SearchNaviBarView *searchNavi;

/**页面主视图*/
@property (nonatomic , strong) UICollectionView *collectionView;

/**数据数组*/
@property (nonatomic , strong) NSMutableArray   *models;

@property (nonatomic, strong) NSMutableArray<HomeADItemEventModel *>*eventArray;

@property (nonatomic, strong) NSMutableArray <SearchKeyWordModel *>*dataArray;

@property (nonatomic, strong) NSMutableArray <SearchKeyWordModel *>*searchHistoryArray;

@property (nonatomic, assign) BOOL hotFold;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self prePareData];
}

- (void)prePareData {
    
//    self.searchHistoryArray
    self.hotFold = NO;
    NSArray *searchWordsEventList = [[TTUserModel sharedObject].userModelDefault valueForKey:@"BA_searchWordsEventList"];

    self.eventArray = @[].mutableCopy;
    if ([searchWordsEventList isKindOfClass:[NSArray class]] && searchWordsEventList.count > 0) {
        for (NSDictionary *dic in searchWordsEventList) {
            HomeADItemEventModel *model = [HomeADItemEventModel modelWithJSON:dic];
            model.eventClickName = [dic valueForKey:@"searchKey"];
            [self.eventArray addObject:model];
        }
    }
    
    [self getLatestHistoryList];
    [self request_hotSearch];
}

- (void)getLatestHistoryList {
    
    NSArray *keyWordArray = [TTUserModel sharedObject].searchHistoryArray;
    self.searchHistoryArray = @[].mutableCopy;
    for (NSString *str in keyWordArray) {
        SearchKeyWordModel *model = [[SearchKeyWordModel alloc] init];
        model.hotWords = str;
        
        CGFloat width = [Utilities getStringWidthWithString:model.hotWords fontSize:12 andHeight:30] + 20;
        if (width > TTScreenWidth - 30) {
            model.keyWordWidth = TTScreenWidth - 30;
        } else {
            model.keyWordWidth = width;
        }        
        [self.searchHistoryArray addObject:model];
    }
    
}

- (void)goSearchResultWithKeyWord:(NSString *)keyWord {

    NSInteger count = 0;
    NSInteger index = 0;
    for (HomeADItemEventModel *model in self.eventArray) {
        if ([model.eventClickName isEqualToString:keyWord]) {
            count++;
            index = [self.eventArray indexOfObject:model];
            [[TT_JumpManager sharedManager] jumpWithModel:self.eventArray[index] completion:^(BOOL success, NSString * _Nonnull message) {}];
            break;
        }
    }
        
    if (count > 0) {

    } else {
        SearchResultSegViewController *vc = [[SearchResultSegViewController alloc] init];
        vc.keyWord = keyWord;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)initView {
    
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.searchNavi];
    
    [self.searchNavi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(kStatusBarHeight);
        make.height.mas_equalTo(NavBar_Height);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.top.mas_equalTo(self.searchNavi.mas_bottom);
    }];
    
    self.searchNavi.searchTF.text = self.keyWord;
}

- (void)goBack {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
//    if (textField.text.length>0) {
        [self goSearchResultWithKeyWord:textField.text];
        [[TTUserModel sharedObject] addSearchHistoryWithKeyWord:textField.text];

//    } else {
//        [SVProgressHUD showErrorWithStatus:@"请输入搜索词"];
//        [SVProgressHUD dismissWithDelay:1];
//    }
    return YES;
}

#pragma mark- 协议方法
//collectionView的协议方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    switch (indexPath.section) {
        case 0:{
            [[TTUserModel sharedObject] addSearchHistoryWithKeyWord:self.dataArray[indexPath.row].hotWords];
            [self goSearchResultWithKeyWord:self.dataArray[indexPath.row].hotWords];

        } break;
        case 1:{
            [self goSearchResultWithKeyWord:self.searchHistoryArray[indexPath.row].hotWords];

        } break;
        default:
            break;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchKeyWordItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchKeyWordItemCellID" forIndexPath:indexPath];
    switch (indexPath.section) {
        case 0:{
            cell.itemTitleLab.text = self.dataArray[indexPath.row].hotWords;
            cell.itemTitleLab.backgroundColor = UIColorHex(0xfff3f9);
        } break;
        case 1:{
            cell.itemTitleLab.text = self.searchHistoryArray[indexPath.row].hotWords;
            cell.itemTitleLab.backgroundColor = UIColorHex(0xF5F7FA);
        } break;
        default:
            break;
    }
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    switch (section) {
        case 0:{
            if (self.hotFold) {
                return 0;
            }
            return self.dataArray.count;
        } break;
        case 1:{
            return self.searchHistoryArray.count;
        } break;
        default:
            break;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    WEAKSELF
    if (kind == UICollectionElementKindSectionHeader) {
        SearchSectionHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchSectionHeader" forIndexPath:indexPath];
        
        headerView.SearchSectionHeaderBlock = ^{
          
            switch (indexPath.section) {
                case 0:{
                    
                    weakSelf.hotFold = !weakSelf.hotFold;
                    [weakSelf.collectionView reloadData];
                    
                } break;
                case 1:{
                    
                    [TT_Alert alert:@"是否删除历史记录" cancleBtnTitle:@"取消" cancleAction:^{
                        
                    } doneBtnTitle:@"确定" doneAction:^{
                        [[TTUserModel sharedObject] clearSearchHistory];
                        weakSelf.searchHistoryArray = @[].mutableCopy;
                        [weakSelf.collectionView reloadData];
                    }];
                    
                } break;
                    
                default:
                    break;
            }
        };
        
        switch (indexPath.section) {
            case 0:{
                headerView.sectionTitle.text = @"热门推荐";
                [headerView.sectionBtn setImage:[UIImage imageNamed:@"search_kejian"] forState:UIControlStateNormal];
                
            } break;
            case 1:{
                headerView.sectionTitle.text = @"历史搜索";
                [headerView.sectionBtn setImage:[UIImage imageNamed:@"search_qingkong"] forState:UIControlStateNormal];

            } break;
            default:
                break;
        }
        
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的度
    return 30;//同一section下请不要改变高度.
}

- (CGFloat)layout:(ZZLayout *)layout widthForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的宽
    
    switch (indexPath.section) {
        case 0:{
            return self.dataArray[indexPath.row].keyWordWidth;//这里可以根据内容传入任意宽度

        } break;
        case 1:{
            return self.searchHistoryArray[indexPath.row].keyWordWidth;//这里可以根据内容传入任意宽度

        } break;
        default:
            break;
    }
    return 20;//这里可以根据内容传入任意宽度
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    return UIEdgeInsetsMake(10, 15, 10, 15);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距
    return 10;
}

- (CGFloat) layout:(ZZLayout *)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距
    return 15;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度
    return CGSizeMake(self.view.bounds.size.width, 44);
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {
    return [UIColor whiteColor];
}

#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeAutomateFloat delegate:self];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - kStatusBarHeight - NavBar_Height) collectionViewLayout:layout];
        _collectionView.delegate = self;_collectionView.dataSource = self;
        
        //注册cell
        [_collectionView registerNib:[UINib nibWithNibName:@"SearchKeyWordItemCell" bundle:nil] forCellWithReuseIdentifier:@"SearchKeyWordItemCellID"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"SearchSectionHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchSectionHeader"];
        
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];
        
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _collectionView.backgroundColor = [UIColor whiteColor];
        
    }
    return _collectionView;
}

- (SearchNaviBarView *)searchNavi {
    
    if (!_searchNavi) {
        _searchNavi = [[NSBundle mainBundle] loadNibNamed:@"SearchNaviBarView"owner:nil options:nil].firstObject;
        [_searchNavi.cancleBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        _searchNavi.searchTF.delegate = self;

    }
    return _searchNavi;
}

- (NSMutableArray<SearchKeyWordModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (NSMutableArray<SearchKeyWordModel *> *)searchHistoryArray {
    if (!_searchHistoryArray) {
        _searchHistoryArray = @[].mutableCopy;
    }
    return _searchHistoryArray;
}

- (void)request_hotSearch {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(1) forKey:@"pageNum"];
    [dic setValue:@(100) forKey:@"pageSize"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_HotSearch];
    WEAKSELF

    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];

//        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];

                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                if ([list isKindOfClass:[NSArray class]]) {
                    weakSelf.dataArray = @[].mutableCopy;
                    for (int i = 0; i < list.count; i++) {
                        
                        SearchKeyWordModel *model = [SearchKeyWordModel modelWithDictionary:list[i]];
                        
                        CGFloat width = [Utilities getStringWidthWithString:model.hotWords fontSize:12 andHeight:30] + 20;
                        if (width > TTScreenWidth - 30) {
                            model.keyWordWidth = TTScreenWidth - 30;
                        } else {
                            model.keyWordWidth = width;
                        }
                        [weakSelf.dataArray addObject:model];
                    }
                    [weakSelf.collectionView reloadData];
                }
                
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [weakSelf.collectionView reloadData];
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
//        [SVProgressHUD dismiss];
    }];
    
    
}

@end
